---
import Markdown from "@components/misc/Markdown.astro";
import PasswordProtection from "@components/PasswordProtection.astro";
import MainGridLayout from "@layouts/MainGridLayout.astro";
import bcryptjs from "bcryptjs";
import CryptoJS from "crypto-js";
import ImageWrapper from "@/components/misc/ImageWrapper.astro";
import PostMetadata from "@/components/PostMeta.astro";
import { siteConfig } from "@/config";
import { Article } from "@/types/article";
import { WebResult } from "@/types/web-result";
import { renderArticle, renderArticleHeadings } from "@/utils/article-renderer";
import { formatDateToYYYYMMDD } from "@/utils/date-utils";
import httpRequest from "../../utils/http";
import { MarkdownHeading } from "astro";

const { id: articleID } = Astro.params;
const article = await httpRequest<WebResult<Article>>({
	url: `/api/article/${articleID}`,
}).then((result) => {
	return result?.data;
});
if (!article) {
	return Astro.redirect("/404/");
}
const articleDescription =
	`${article.content.substring(0, 100)}......` || article.title;
let articleHTML = "";
let articleHeadings: MarkdownHeading[] = [];

let encryptedContent = "";
let passwordHash = "";
let isEncrypted = false;
if (isEncrypted) {
	// 对于加密文章，我们将使用markdown内容进行加密
	// 在客户端解密后，会通过JavaScript重新渲染markdown
	const contentToEncrypt = article.contentData.content || article.content;

	// 使用AES加密内容
	encryptedContent = CryptoJS.AES.encrypt(
		contentToEncrypt,
		article.title,
	).toString();

	// 生成密码哈希
	const saltRounds = 10;
	passwordHash = bcryptjs.hashSync(article.title, saltRounds);
} else {
    getArticleHTML(article);
}

function getArticleHTML(article: Article) {
    if (articleHTML) {
        return articleHTML;
    }
    articleHTML = renderArticle(article);
    articleHeadings = renderArticleHeadings(articleHTML);
    return articleHTML;
}

const jsonLd = {
	"@context": "https://schema.org",
	"@type": "BlogPosting",
	headline: article.title,
	description: articleDescription,
	keywords: [],
	author: {
		"@type": "Person",
		name: article.author,
		url: Astro.site,
	},
	datePublished: formatDateToYYYYMMDD(new Date(article.publish_time)),
	inLanguage: siteConfig.lang.replace("_", "-"),
	// TODO include cover image here
};
---

<MainGridLayout
    banner={article.cover}
    title={article.title}
    description={articleDescription}
    lang={siteConfig.lang.replace("_", "-")}
    setOGTypeArticle={true}
    postSlug={article.id.toString()}
    headings={articleHeadings}
>
    <script
        is:inline
        slot="head"
        type="application/ld+json"
        set:html={JSON.stringify(jsonLd)}
    />

    <div
        class="flex w-full rounded-[var(--radius-large)] overflow-hidden relative mb-4"
    >
        <div
            id="post-container"
            class:list={[
                "card-base z-10 px-6 md:px-9 pt-6 pb-4 relative w-full ",
                {},
            ]}
        >
            <!-- title -->
            <div class="relative onload-animation">
                <div
                    data-pagefind-body
                    data-pagefind-weight="10"
                    data-pagefind-meta="title"
                    class="transition w-full block font-bold mb-3
                    text-3xl md:text-[2.25rem]/[2.75rem]
                    text-black/90 dark:text-white/90
                    md:before:w-1 before:h-5 before:rounded-md before:bg-[var(--primary)]
                    before:absolute before:top-[0.75rem] before:left-[-1.125rem]"
                >
                    {article.title}
                </div>
            </div>

            <!-- metadata -->
            <div class="onload-animation">
                <PostMetadata
                    class="mb-5"
                    published={new Date(article.publish_time)}
                    updated={new Date(article.update_time)}
                    tags={[]}
                    category={article.sort_name}
                />
                {
                    !article.cover && (
                        <div class="border-[var(--line-divider)] border-dashed border-b-[1px] mb-5" />
                    )
                }
            </div>

            <!-- always show cover as long as it has one -->

            {
                article.cover && (
                    <ImageWrapper
                        id="article-cover"
                        src={article.cover}
                        basePath="/"
                        class="mb-8 rounded-xl banner-container onload-animation"
                    />
                )
            }

            {
                isEncrypted ? (
                    <PasswordProtection
                        encryptedContent={encryptedContent}
                        passwordHash={passwordHash}
                    />
                ) : (
                    <>
                        <Markdown
                            class="mb-6 markdown-content onload-animation"
                            set:html={getArticleHTML(article)}
                        >
                        </Markdown>
                    </>
                )
            }
        </div>
    </div>
</MainGridLayout>
